/*
 * @Author: your name
 * @Date: 2020-02-25 16:34:44
 * @LastEditTime: 2020-05-25 20:00:08
 * @LastEditors: huacong
 * @Description: In User Settings Edit
 * @FilePath: \pc\src\pages\Analysis\SupplyContrast\models\items.js
 */
import _ from 'lodash';
import * as api from '@/services/SupplyPlanReportFormMgr';
import * as utils from '../utils/treeUtils';

const Model = {
  namespace: 'SupplyPlanReportForm',
  state: {
    all: [],
    items: [],
    expandedRowKeys: [],
    level: 'project',
  },
  effects: {
    *init({ payload, callback }, { call, put, select }) {
      yield put({
        type: 'save',
        payload: { items: [] },
      });
      const response = yield call(api.supplyCompareReportUsingGET, payload);
      const level = yield select(state => state.SupplyPlanReportForm.level);
      if (response && response.code === 1 && !_.isEmpty(response.data)) {
        const uniqData = _.unionBy(response.data, 'id');
        _.each(uniqData, v => {
          const x = v;
          if (v.name === '旭辉集团') x.name = '全部';
        });
        const all = _.cloneDeep(uniqData);
        const levelTree = utils.levelTree(uniqData, level);
        const expandedRowKeys = utils.getExpandedRowKeys(levelTree);

        const treeData = utils.buildTree(levelTree);

        yield put({
          type: 'save',
          payload: { all, items: treeData, expandedRowKeys },
        });
      }
      if (callback) callback(response);
    },
    *level({ payload, callback }, { call, put, select }) {
      const all = yield select(state => state.SupplyPlanReportForm.all);
      const { level } = payload;
      const levelTree = utils.levelTree(all, level);
      const expandedRowKeys = utils.getExpandedRowKeys(levelTree);
      const treeData = utils.buildTree(levelTree);
      yield put({
        type: 'save',
        payload: { level, items: treeData, expandedRowKeys },
      });
    },
  },
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};
export default Model;
